//
//  UserAccountViewModel.swift
//  weiboSwift1.0
//
//  Created by xuNick on 16/4/20.
//  Copyright © 2016年 NN. All rights reserved.
//

import UIKit



class UserAccountViewModel: NSObject {
    
//    let WB_APP_KEY:String = "4117371138"
//    
//    let WB_REDIRECT_URI = "https://www.baidu.com/"
//    
//    let WB_APP_SECRET = "697bfcf5ae5d77af9bc775963900beeb"
    

    static let shareUserAccountViewModel: UserAccountViewModel = UserAccountViewModel()
    
    
    override init() {
        super.init()
        // 代表当当前 ViewModel 初始化的时候，就尝试去沙盒中读取数据
        account = self.accountInSanbox()
    }

    
    
    func loadAccessToken(code: String, finished:(issuccess:Bool) -> ()){
    
             let urlString = "https://api.weibo.com/oauth2/access_token"
    
    
            let params = [
                "client_id": WB_APP_KEY,
                "client_secret": WB_APP_SECRET,
                "grant_type": "authorization_code",
                "code": code,
                "redirect_uri": WB_REDIRECT_URI
            ]
        NetworkingTool.shareWorkTools.request(RequestMethod.Post, urlString: urlString, parameters: params) { (reponseObject, error) -> () in
            if error != nil{
                print(error)
                return
            }
    
            guard let dict = reponseObject as? [String : AnyObject] else{
                print("数据加载不正确")
                return
            }
            let account = UserAccount(dict: dict)
            print(account)
            finished(issuccess: true)
            self.loadUserInfo(account)
    
            }
    
        }
    
    
       private  func loadUserInfo(account: UserAccount){
            // 请求地址
            let urlString = "https://api.weibo.com/2/users/show.json"
    
            // 请求参数
            let params = [
                "access_token": account.access_token ?? "",
                "uid": account.uid ?? ""
            ]
    
            // 发送请求
            NetworkingTool.shareWorkTools.request(urlString: urlString, parameters: params) { (responseObject, error) -> () in
    
                if error != nil {
//                    SVProgressHUD.showErrorWithStatus("网络错误")
                    return
                }
                // 判断返回数据是否是字典
                guard let dict = responseObject as? [String: AnyObject] else {
                    print("后台返回的数据格式不对")
                    return
                }
                // 如果等于前面是可选值的话，就使用 as? 如果是必选值，就使用 as!
                account.name = dict["name"] as? String
                account.avatar_large = dict["avatar_large"] as? String
    
                print(account.uid)
            // #warning TODO: 保存登录信息
                self.saveUserInfo(account)
                
                self.account = account
            //跳转控制器
            }
        }
    
    // 当前登录的用户的帐户信息 --
    var account: UserAccount?
    
    var accessToken: String? {
        return self.account?.access_token
    }

    
    
    
    
    var isLogin: Bool {
        
        // 1. 是否有 accessToken
        if accessToken == nil {
            return false
        }
        //        guard let accessToken = self.account?.access_token else {
        //            // 如果没有accessToken就代表没有登录，所以return false
        //            return false
        //        }
        
        // 2. 判断 accessToken 是否过期
        // 如果判断 accessToken 是否过期 --> 取到过期时间，与当前时间进行对比，如果过期时间比当前时间小，就代表过期
        
        // 取到过期时间
        guard let expiresDate = self.account?.expiresDate else {
            return false
        }
        // 与当前时间进行对比  --> 当前时间比过期时间小 return true
        if NSDate().compare(expiresDate) == .OrderedAscending {
            // 没有过期，就返回true （代表登录）
            return true
        }
        return false
    }
    
        private func saveUserInfo(account:UserAccount){
            //沙盒路径
            let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
            //保存.
            NSKeyedArchiver.archiveRootObject(account, toFile: path)
        }
    
        private func accountInSanbox() -> UserAccount? {
            // 测试解档
            let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
            let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount
            return result
        }
    


}
